// 登录、注册接口
const login = require('koa-router')();
const bodyparser = require('koa-bodyparser');
const koabody = require('koa-body');
const { sign } = require('jsonwebtoken');

const db = require('../utils/db');

/**
 * 为了获取post传递过来的参数
 * bodyparser获取不到form-data格式的参数，
 * 所以添加koa-body中间件
*/
login.use( bodyparser(), koabody({ multipart: true }) ); 

login.post( '/register', async ctx => {

    let { username, password } = ctx.request.body;

    let userinfo = await new Promise( ( resolve, reject ) => {
        return db.query( `select * from user where username =  '${ username }'`, ( err, data ) => {
            if( err ) { throw err }
            resolve( data )
        } )
    } )

    if( userinfo.length == 0 ) { 
        // 该账号不存在，走注册程序
        let token = sign( { username, password }, 'jdf_token', { expiresIn: '2h' } );

        let results = await new Promise( ( resolve, reject ) => {
            return db.query( `insert into user ( username, password, token ) values ( '${ username }', '${ password }', '${ token }' )`, ( err, data ) => {
                if( err ) { throw err }

                let result = {
                    code: 1,
                    msg: '注册成功',
                    username,
                    token
                }

                resolve( result )
            } )
        } )

        ctx.body = results;
    }else {
        // 存在该账号，返回token
        if( userinfo[0].password == password ) {
            ctx.body = {
                code: 1,
                msg: '登录成功',
                username,
                token: userinfo[0].token
            }
        }else {
            ctx.body = {
                code: 0,
                msg: '登录失败，密码错误'
            }
        }
    }
} )

module.exports = login
